package com.dongdongshop.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.dongdongshop.data.Result;
import com.dongdongshop.em.ResultEnum;
import com.dongdongshop.pojo.*;
import com.dongdongshop.pojo.VO.SpecificationVO;
import com.dongdongshop.pojo.VO.TbTypeTemplateVO;
import com.dongdongshop.service.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("seller")
public class TbSellerController {

    @DubboReference
    private TbSellerService tbSellerService;
    @DubboReference
    private TbItemCatService tbItemCatService;
    @DubboReference
    private TbTypeTemplateService tbTypeTemplateService;
    @DubboReference
    private TbGoodsService tbGoodsService;
    @DubboReference
    private TbSpecificationService tbSpecificationService;


    @RequestMapping("goods")
    private String goods() {
        System.out.println("----------------------------------------------------------");
        return "admin/goods_edit";
    }

    @RequestMapping("getGoods")
    @ResponseBody
    private Result getGoods(Long pid) {
        List<TbItemCat> tbItemCats = tbItemCatService.selectPid(pid);
        if (tbItemCats == null) {
            return Result.response(ResultEnum.ERROR);
        }
        return Result.response(ResultEnum.SUCCESS).setData(tbItemCats);
    }


    @RequestMapping("getGoodsType")
    @ResponseBody
    private Result getGoodsType(Long typeId) {
        TbTypeTemplate tbTypeTemplate = tbTypeTemplateService.selectTid(typeId);
        //从模板中取出规格
        String specIds = tbTypeTemplate.getSpecIds();
        List<SpecificationVO> voList = JSONObject.parseArray(specIds, SpecificationVO.class);

        for (SpecificationVO vo :voList) {
            List<TbSpecificationOption> optionList = tbSpecificationService.selectBySpecId(vo.getId());
            vo.setOptionList(optionList);
        }
        TbTypeTemplateVO tbTypeTemplateVO = new TbTypeTemplateVO();
        tbTypeTemplateVO.setId(tbTypeTemplate.getId());
        tbTypeTemplateVO.setBrandIds(tbTypeTemplate.getBrandIds());
        tbTypeTemplateVO.setName(tbTypeTemplate.getName());
        tbTypeTemplateVO.setCustomAttributeItems(tbTypeTemplate.getCustomAttributeItems());
        tbTypeTemplateVO.setSpecIds(voList);

        if (tbTypeTemplate == null) {
            return Result.response(ResultEnum.ERROR);
        }
        return Result.response(ResultEnum.SUCCESS).setData(tbTypeTemplateVO);
    }

    @RequestMapping("insertAll")
    @ResponseBody
    private Result insertAll(TbGoods tbGoods, TbGoodsDesc tbGoodsDesc) {
        //使用shiro时，如果正常登陆（执行subject.login(token)成功）就能在全局通过SecurityUtils.getSubject().getPrincipal()获取用户信息
        Subject subject = SecurityUtils.getSubject();
        TbSeller seller = (TbSeller) subject.getPrincipal();
        tbGoods.setSellerId(seller.getSellerId());
        tbGoods.setAuditStatus("0");
        boolean b = tbGoodsService.insertByGoods(tbGoods, tbGoodsDesc);
        if (b) {
            return Result.response(ResultEnum.SUCCESS);
        }
        return Result.response(ResultEnum.ERROR);
    }
    @RequestMapping("upload")
    @ResponseBody
    public Result upload(@RequestParam("myFile") MultipartFile newsImg) {


        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String https = "https://";
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId ="LTAI5tHN3yEyuvM1CgMMJaAo";
        String accessKeySecret ="tDx9LtZQpmpVhASbWq7UrGuXEtiKE0";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(https + endpoint, accessKeyId, accessKeySecret);


        String imagePath = "image/" + newsImg.getOriginalFilename();
        String buket = "dongdong220110";

        // 创建PutObjectRequest对象。
        // 依次填写Bucket名称（例如examplebucket）和Object完整路径（例如exampledir/exampleobject.txt）。Object完整路径中不能包含Bucket名称。
        PutObjectRequest putObjectRequest = null;
        try {
            putObjectRequest = new PutObjectRequest(buket, imagePath, newsImg.getInputStream());
            ossClient.putObject(putObjectRequest);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 关闭OSSClient。
        ossClient.shutdown();
        //String dowloadUrl = https + buket + "." + endpoint + "/" + imagePath;
        StringBuilder builder = new StringBuilder();
        builder.append(https).append(buket).append(".").append(endpoint).append("/").append(imagePath);
        return Result.response(ResultEnum.SUCCESS).setData(builder.toString());
    }

}
